package com.rich.web.servlet;

import java.util.List;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.rich.constant.Constant;
import com.rich.domain.Order;
import com.rich.domain.OrderItem;
import com.rich.service.OrderService;
import com.rich.utils.BeanFactory;
import com.rich.utils.JsonUtil;

import net.sf.json.JSONArray;
import net.sf.json.JsonConfig;

/**
 * 后台订单模块
 * @author zhang
 *
 */
@WebServlet("/adminOrder")
public class AdminOrderServlet extends BaseServlet {
	private static final long serialVersionUID = 1L;

	OrderService os = (OrderService) BeanFactory.getBean("OrderService");
	
	/**
	 * 按状态查询订单列表
	 * @param request
	 * @param response
	 * @return
	 */
	public String findAllByState(HttpServletRequest request, HttpServletResponse response) {
		try {
			String state = request.getParameter("state");
			List<Order> list = os.findAllByState(state);
			request.setAttribute("oList", list);
			return "/admin/order/list.jsp";
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException();
		}
	}

	/**
	 * 后台获取订单详情
	 * @param request
	 * @param response
	 * @return
	 */
	public String showDetail(HttpServletRequest request, HttpServletResponse response) {
		response.setContentType("text/html;charset=utf-8");
		try {
			String oid = request.getParameter("oid");
			//获取order
			Order order = os.getById(oid);
			if(order != null) {
				//获取订单项列表,并返回json
				List<OrderItem> items = order.getItems();
				if(items != null && items.size() > 0) {
					//全部字段获取
					//response.getWriter().println(JsonUtil.list2json(items));
					
					//获取不想要的字段
					//1.选择要排除的字段
					JsonConfig config = JsonUtil.configJson(new String[] {"order","itemId","subtotal","address"});
					//2.排除
					response.getWriter().println(JSONArray.fromObject(items, config));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 修改订单状态
	 */
	public String updateState(HttpServletRequest request, HttpServletResponse response) {
		try {
			//获取oid
			String oid = request.getParameter("oid");
			
			//获取订单
			Order order = os.getById(oid);
			//修改状态，跟新状态
			order.setState(Constant.ORDER_SEATE_SEND);
			os.update(order);
			response.sendRedirect(request.getContextPath()+"/adminOrder?method=findAllByState&state=1");
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return null;
	}
}
